#!/bin/bash

OS=$(uname -s)

if [ "$OS" = "Darwin" ]; then
    echo "This is macOS (Darwin)"
    file="https://v2rayshare.githubrowcontent.com/$(date +"%Y")/$(date +"%m")/$(date +"%Y%m%d").yaml"
elif [ "$OS" = "Linux" ]; then
    echo "This is Linux"
    file="https://v2rayshare.githubrowcontent.com/$(date +"%Y")/$(date +"%m")/$(date +"%Y%m%d").yaml"
else
    echo "Unknown OS: $OS"
    return 2>/dev/null
fi

echo "downloading config $file"

output_file="./config.yaml"

if [ -f "$output_file" ]; then
    rm -f "$output_file"
fi

source ./off.sh

curl  --connect-timeout 5 --max-time 20 -o "$output_file" "$file"

if [ $? -gt 0 ]; then
    if [ "$OS" = "Darwin" ]; then
        echo "This is macOS (Darwin)"
        file="https://v2rayshare.githubrowcontent.com/$(date +"%Y")/$(date +"%m")/$(date -v-1d +"%Y%m%d").yaml"
    elif [ "$OS" = "Linux" ]; then
        echo "This is Linux"
        file="https://v2rayshare.githubrowcontent.com/$(date -d "1 day ago"  +"%Y")/$(date -d "1 day ago" +"%m")/$(date -d "1 day ago" +"%Y%m%d").yaml"
    else
        echo "Unknown OS: $OS"
        return 2>/dev/null
    fi
fi

echo "downloading config $file"
curl  --connect-timeout 10 --max-time 20 -o "$output_file" "$file"

if [ $? -eq 0 ]; then
    echo -e "\033[0;32m ./download-config.sh executed successfully \033[0m"
else
    echo "\033[0;31m failed to execute ./download-config.sh \033[0m"
    return 1 
fi

echo "============config.yaml================"

head "$output_file"

echo "============config.yaml================"


if [ "$OS" = "Darwin" ]; then
    echo "This is macOS (Darwin)"
    sed -i '' 's/allow-lan: false/allow-lan: true/' "$output_file" 
elif [ "$OS" = "Linux" ]; then
    echo "This is Linux"
    sed -i 's/allow-lan: false/allow-lan: true/' "$output_file" 
else
    echo "033[0;31m change config fail\033[0m"
    return 2>/dev/null
fi


echo "============config.yaml================"

head "$output_file"

echo "============config.yaml================"

# OS=$(uname -s)

# if [ "$OS" = "Darwin" ]; then
#     echo "This is macOS (Darwin)"
#     sed -i '' '1a\'$'\n''bind-address: 0.0.0.0'$'\n' "$output_file" | head 
# elif [ "$OS" = "Linux" ]; then
#     echo "This is Linux"
#     sed -i '1a \bind-address: 0.0.0.0'$'\n' config.yaml "$output_file" | head 
#     echo "finish bind-address: 0.0.0.0" 
# else
#     echo "Unknown OS: $OS"
#     exit
# fi

